package com.common.controller;

import com.common.service.BaseService;
import com.common.service.UserService;
import com.common.tools.ServletUtil;
import com.common.tools.query.PropertyFilter;
import com.common.tools.query.QueryDTO;
import com.common.tools.query.SpecificationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @classDescription:
 * @author:xiayingjie
 * @createTime:16/8/6
 */

public class BaseController {

    @Autowired
    protected UserService userService;

    /**
     * 分页整合
     * @param request
     * @param response
     * @param queryDTO
     * @param service
     * @param clz
     * @param path
     */
    public void list(HttpServletRequest request, HttpServletResponse response,QueryDTO queryDTO,BaseService service,Class clz,String path) {

        Map<String,String> searchMap= ServletUtil.getParametersStartingWith(request, "search");

        //查询结果
        Specification specification= SpecificationUtil.bySearchFilter(searchMap, clz);
        PageRequest pageRequest=SpecificationUtil.getPageRequest(queryDTO);
        Page page = service.findAll(specification,pageRequest);
        //获取查询条件
        Map conditionMap= PropertyFilter.parseCondition(searchMap, queryDTO, path);

        PropertyFilter.setAttribute(request,searchMap);
        request.setAttribute("conditionMap",conditionMap);
        request.setAttribute("pageInfo", page);
        request.getSession().setAttribute("currentPage",path+"?"+PropertyFilter.parseUrl(searchMap,queryDTO));

    }

    /**
     * 获取分页map
     * @param page
     * @param size
     * @param allSize
     * @param allPage
     * @return
     */
    public Map putPage(int page,int size,long allSize,int allPage){
        Map map=new HashMap();
        map.put("page", page);
        map.put("totalPage", allPage);
        map.put("size", size);
        map.put("totalSize", allSize);
        return map;
    }
}
